/*
 * Copyright [2016] [zhangsong <songm.cn>].
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package cn.vser.server;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.util.List;

import com.google.gson.reflect.TypeToken;

import cn.vser.server.entity.AVparam;
import cn.vser.server.entity.Configuration;
import cn.vser.server.entity.Result;
import cn.vser.server.entity.StmaddrVo;
import cn.vser.server.utils.AuthurlUtil;
import cn.vser.server.utils.HttpUtil;
import cn.vser.server.utils.JsonUtils;

/**
 * API
 * 
 * @author zhangsong
 *
 */
public class VserApi {

    private static final String ENCODING = "utf-8";
    private static VserApi instance;

    private String server;
    private String vserSdkKey;
    private String vserSdkSecret;

    private static void _instance() {
        synchronized (VserApi.class) {
            if (instance == null) {
                instance = new VserApi();
            }
        }
    }
    
    public static VserApi getInstance() {
        _instance();
        if (instance.server == null
                || instance.vserSdkKey == null
                || instance.vserSdkSecret == null) {
            throw new IllegalArgumentException("initialize error");
        }
        return instance;
    }

    public static void initialize(String vserSdkKey, String vserSdkSecret, String server) {
        _instance();
        instance.server = server;
        instance.vserSdkKey = vserSdkKey;
        instance.vserSdkSecret = vserSdkSecret;
    }

    /**
     * 获取Token
     * 
     * @param uid
     * @param nick
     * @param avatar
     * @return
     * @throws ApiException
     */
    public Configuration getConfiguration()
            throws ApiException {
        String res = null;
        try {
            String url = server + "/back/configuration.json";
             HttpURLConnection conn = HttpUtil.createHttpConnection(
                    vserSdkKey, vserSdkSecret, url);
            HttpUtil.setConnection("method", "GET", conn);
            HttpUtil.setBodyParameter(null, conn);
            res = HttpUtil.returnResult(conn);
        } catch (HttpConnException e) {
            throw new RuntimeException(e);
        }
        
        Type type = new TypeToken<Result<Configuration>>() { }.getType();
        Result<Configuration> r = JsonUtils.fromJson(res, type);
        if (!r.getSucceed()) {
            throw new ApiException(r.getErrorCode(), r.getErrorDesc());
        }
        return r.getData();
    }
    
    public AVparam getAVparam()
            throws ApiException {
        String res = null;
        try {
            String url = server + "/back/avparam/get.json";
             HttpURLConnection conn = HttpUtil.createHttpConnection(
                    vserSdkKey, vserSdkSecret, url);
            HttpUtil.setConnection("method", "GET", conn);
            HttpUtil.setBodyParameter(null, conn);
            res = HttpUtil.returnResult(conn);
        } catch (HttpConnException e) {
            throw new RuntimeException(e);
        }
        
        Type type = new TypeToken<Result<AVparam>>() { }.getType();
        Result<AVparam> r = JsonUtils.fromJson(res, type);
        if (!r.getSucceed()) {
            throw new ApiException(r.getErrorCode(), r.getErrorDesc());
        }
        return r.getData();
    }
    
    public StmaddrVo getStmaddrByScode(String scode)
            throws ApiException {
        StringBuilder sb = new StringBuilder();
        sb.append("scode=").append(scode);
        
        String res = null;
        try {
            String url = server + "/back/stmaddr/get.json?" + sb.toString();
             HttpURLConnection conn = HttpUtil.createHttpConnection(
                    vserSdkKey, vserSdkSecret, url);
            HttpUtil.setConnection("method", "GET", conn);
            HttpUtil.setBodyParameter(sb, conn);
            res = HttpUtil.returnResult(conn);
        } catch (HttpConnException e) {
            throw new RuntimeException(e);
        }
        
        Type type = new TypeToken<Result<StmaddrVo>>() { }.getType();
        Result<StmaddrVo> r = JsonUtils.fromJson(res, type);
        if (!r.getSucceed()) {
            throw new ApiException(r.getErrorCode(), r.getErrorDesc());
        }
        return r.getData();
    }
    
    public String getPushAddr(String server, String scode, String sname, String authSecret, String uid)
            throws UnsupportedEncodingException, URISyntaxException {
        String url = null;
        if (server.endsWith("/")) {
            url = server + scode;
        } else {
            url = server + "/" + scode;
        }
        return AuthurlUtil.getAuthurl(url, uid, authSecret, sname);
    }
    
    public String getPullAddr(String server, String scode, String authSecret, String uid)
            throws UnsupportedEncodingException, URISyntaxException {
        String url = null;
        if (server.endsWith("/")) {
            url = server + scode;
        } else {
            url = server + "/" + scode;
        }
        return AuthurlUtil.getAuthurl(url, uid, authSecret, null);
    }

    public List<StmaddrVo> getStmaddrs(Integer stype) throws ApiException {
        StringBuilder sb = new StringBuilder();
        if (stype != null) {
            sb.append("stype=").append(stype);
        }
        
        String res = null;
        try {
            String url = server + "/back/stmaddr/list.json?" + sb;
            HttpURLConnection conn = HttpUtil.createHttpConnection(
                    vserSdkKey, vserSdkSecret, url);
            HttpUtil.setConnection("method", "GET", conn);
            HttpUtil.setBodyParameter(sb, conn);
            res = HttpUtil.returnResult(conn);
        } catch (HttpConnException e) {
            throw new RuntimeException(e);
        }
        
        Type type = new TypeToken<Result<List<StmaddrVo>>>() { }.getType();
        Result<List<StmaddrVo>> r = JsonUtils.fromJson(res, type);
        if (!r.getSucceed()) {
            throw new ApiException(r.getErrorCode(), r.getErrorDesc());
        }
        return r.getData();
    }
}
